package com.jxd.dianping.service.impl;

import com.jxd.dianping.common.BusinessException;
import com.jxd.dianping.common.EmBusinessError;
import com.jxd.dianping.dao.CategoryModelMapper;
import com.jxd.dianping.model.CategoryModel;
import com.jxd.dianping.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class CategoryServiceImpl implements CategoryService  {

    @Autowired
    private CategoryModelMapper categoryModelMapper;

    @Override
    public CategoryModel create(CategoryModel categoryModel) throws BusinessException {
        categoryModel.setCreateAt(new Date());
        categoryModel.setUpdateAt(new Date());
        // 品类名称唯一
        try {
            categoryModelMapper.insertSelective(categoryModel);
        } catch (DuplicateKeyException ex) {
            throw new BusinessException(EmBusinessError.CATEGORY_NAME_DUP);
        }
        return get(categoryModel.getId());
    }

    @Override
    public CategoryModel get(Integer id) throws BusinessException {
        CategoryModel categoryModel = categoryModelMapper.selectByPrimaryKey(id);
        if (Objects.isNull(categoryModel)) {
            throw new BusinessException(EmBusinessError.CATEGORY_NOT_EXIST);
        }
        return categoryModel;
    }

    @Override
    public List<CategoryModel> selectAll() {
        return categoryModelMapper.selectAll();
    }

    @Override
    public Integer countAllCategory() {
        return categoryModelMapper.countAllCategory();
    }
}
